package org.qing.reactive.controller;

import java.time.Duration;
import java.util.Date;
import java.util.Map.Entry;
import java.util.UUID;

import org.qing.reactive.entity.User;
import org.qing.reactive.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveHashOperations;
import org.springframework.data.redis.core.ReactiveListOperations;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Slf4j
@RestController
public class UserController {

	@Autowired
	private UserService service;

	@Autowired
	private ReactiveRedisTemplate<String, Object> redisTemplate;

	@RequestMapping("/redis")
	public Flux<Entry<String, Object>> redis() {
		String key = "test";
		ReactiveHashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
		ReactiveListOperations<String, Object> listOps = redisTemplate.opsForList();
		for (int i = 0; i < 10; i++) {
			Mono<Boolean> monoAction = hashOps.put(key, UUID.randomUUID().toString(), new Date());
			listOps.rightPush(key+"List", new Date());
			redisTemplate.opsForValue().set("key1","value1");
			monoAction.subscribe(action -> log.info("monoAction=[{}]", action));
		}
		redisTemplate.expire(key, Duration.ofMillis(60000));
		Flux<Entry<String, Object>> fluxHash = hashOps.entries(key);
		fluxHash.subscribe(entry -> log.info("hashKey=[{}], hashValue=[{}]", entry.getKey(), entry.getValue()));
		return fluxHash;
	}

	@RequestMapping("/get/one")
	public Mono<String> getOne() {
		return Mono.just("Hello webflux");
	}

	@RequestMapping("/get/all")
	public Flux<User> findAll() {
		Flux<User> fluxUser = service.findAll();
		// 这里需要消费才行。否则无法真正操作.
		fluxUser.subscribe(user -> {
			log.info("user=[{}]", JSON.toJSONString(user));
			redisTemplate.opsForList().rightPush("userTestKey", user);
		});
		return fluxUser;
	}

}
